package com.yvan.leto.server.dao;

import com.google.common.collect.Lists;
import com.yvan.leto.SegmentHelper;
import com.yvan.leto.server.domain.Project;
import com.yvan.leto.server.domain.Segment;
import com.yvan.leto.server.utils.FileUtils;
import com.yvan.platform.JsonWapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * Created by luoyifan on 2018/6/16.
 */
@Slf4j
public class ProjectPersistent {

    public static final String PROJECT_DIRECTORY = "projects";
    private final String projectPath;


    public ProjectPersistent(String basePath) {
        this.projectPath = FileUtils.normalizePath(basePath, PROJECT_DIRECTORY);
    }

    public String[] projectFindAll() {
        File[] files = FileUtils.listFile(projectPath);
        if (files == null) {
            return new String[0];
        }
        String[] r = new String[files.length];
        int i = 0;
        for (File f : files) {
            String n = f.getName();
            if (n.toLowerCase().endsWith(".yml")) {
                n = n.substring(0, n.length() - 4);
            }
            r[i] = n;
            i++;
        }
        return r;
    }

    public Project projectFindByName(String projectName) {
        JsonWapper jw = FileUtils.readYaml(projectPath, projectName + ".yml");
        Project project = loadProject(jw);
        project.setName(projectName);
        return project;
    }

    private Project loadProject(JsonWapper jw) {
        Project project = new Project();
        project.setSegments(Lists.newArrayList());

        for (String segmentFullName : jw.asDic("segments").keys()) {

            String[] segmentPaths = jw.asObject(String[].class, "segments", segmentFullName);
            List<String> normalizedSegmentPaths = Lists.newArrayList();
            for (String segmentPath : segmentPaths) {
                normalizedSegmentPaths.add(FileUtils.normalizePath(segmentPath));
            }

            project.getSegments().add(
                    new Segment(SegmentHelper.getSegmentName(segmentFullName),
                            SegmentHelper.getSegmentExt(segmentFullName),
                            normalizedSegmentPaths)
            );
        }
        return project;
    }
}
